import logging

import requests
import json
from urllib import parse
from hyper.contrib import HTTP20Adapter

# 使用工具网站根据公网ip查询所在省市
# 但是这个接口需要cookie，暂时还没找到方法
class WhereAddress:
    url = 'https://tool.lu/ip/ajax.html'
    Form_data = {}
    Headers = {}

    def __init__(self):
        self.Form_data = {
            'ip': ''
        }

        # cookie中Hm_lpvt值为秒时间戳
        # _access应该是由包括时间戳的几个值生成的
        self.Headers = {
            ':authority': 'tool.lu',
            ':method': 'POST',
            ':path': '/ip/ajax.html',
            ':scheme': 'https',
            'accept': 'application/json, text/javascript, */*;'
                      'q=0.01',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;'
                               'q=0.9',
            'content-length': '',
            'content-type': 'application/x-www-form-urlencoded;'
                            'charset=UTF-8',
            'cookie': 'slim_session=%7B%22slim.flash%22%3A%5B%5D%7D;'
                      'uuid=fb254319-10fe-4729-c7ef-9d0b73108342;'
                      'Hm_lvt_0fba23df1ee7ec49af558fb29456f532=1627398788,1627442303,1627978361,1628040040;'
                      'Hm_lpvt_0fba23df1ee7ec49af558fb29456f532=1628057479;'
                      '_access=0e728b216629c8f2a3d1f698dc383e2487caf4136dc69dba81501c9a2d5c8cf3',
            'origin': 'https://tool.lu',
            'referer': 'https://tool.lu/ip/',
            'sec-ch-ua': '"Chromium";'
                         'v="92", " Not A;Brand";'
                         'v="99", " Google Chrome";'
                         'v="92"',
            'sec-ch-ua-mobile': '?0',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest'
        }

    def setRequestData(self, ip):
        self.Form_data['ip'] = ip
        self.Headers['content-length'] = str(len(parse.urlencode(self.Form_data).encode('utf-8')))

    def getaddress(self, ip):
        '''
        根据公网ip获取所在省市
        :param ip:
        :return:
        '''
        # 设置请求参数
        self.setRequestData(ip)

        # 获取编码结果
        sessions = requests.session()
        sessions.mount("https://tool.lu/", HTTP20Adapter())
        try:
            response = sessions.post(url=self.url, data=self.Form_data, headers=self.Headers)
            result = json.loads(response.text)
            if 'text' in result:
                try:
                    text = result['text']['taobao']
                    return text.split()[1:3]
                except:
                    logging.info('get address failed!')
                    return None
        except:
            logging.info('sessions.post exceptionc!')
            return None


if __name__ == '__main__':
    where = WhereAddress()
    print(where.getaddress('112.49.39.82'))
